import React, {useState, JSX} from "react";  // 导入所需的模块
import {View} from "@tarojs/components";
import './index.scss';

export interface ITabItem {
  name: string;
  label: string;
}
export interface ITabs {  // 定义组件接收的props类型
  list: Array<ITabItem>
  onChange?: (string) => void;
}

export const Tabs: React.FC<ITabs> = ({list, onChange}): JSX.Element => {  // 使用泛型定义组件的props类型
  const [tabActive, setTabActive] = useState(list[0].name);  // 使用useState定义状态

  const onTab = (name: string) => {  // 定义点击tab的事件处理函数
    setTabActive(name);  // 更新选中的tab
    // 如果定义了onChange回调函数，则调用它
    typeof onChange === 'function' && onChange(name);
  };

  return (
    <View className='Tabs flex'>
      {list.map(item => (
        <View
          key={item.name}
          className='tabItem align-center justify-center'
          onClick={() => onTab(item.name)}  // 调用事件处理函数
        >
          <View
            className='label'
            style={{borderBottomColor: tabActive === item.name ? '#409EFF' : 'transparent'}}
          >
            {item.label}
          </View>
        </View>
      ))}
    </View>
  );
};

export default Tabs;
